package com.minelx.util.common;

import java.util.function.BiConsumer;
import java.util.function.Function;

public class TreeNode<E> {
	private final Node<E> root;

	public TreeNode(Node<E> root) {
		this.root = root;
	}

	public <R> R convert(Function<? super Node<E>, R> factory, BiConsumer<R, R> addChild) {
		return convert0(root, factory, addChild);
	}

	private <R> R convert0(Node<E> currentRoot, Function<? super Node<E>, R> factory, BiConsumer<R, R> addChild) {
		R destinationRoot = factory.apply(currentRoot);
		for (Node<E> child : currentRoot.children()) {
			addChild.accept(destinationRoot, convert0(child, factory, addChild));
		}
		return destinationRoot;
	}
}
